package com.ly.lypopupwindowdemo.activity;

import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import com.ly.lypopupwindowdemo.R;
import com.ly.lypopupwindowdemo.bean.EntityStudent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class ParseActivity extends AppCompatActivity implements View.OnClickListener {

    TextView content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parse);

        findViewById(R.id.btn1).setOnClickListener(this);
        findViewById(R.id.btn2).setOnClickListener(this);
        findViewById(R.id.btn3).setOnClickListener(this);
        content = (TextView) findViewById(R.id.content);



    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn1:
                naviveParse();
                break;
            case R.id.btn2:
                domParse();
                break;
            case R.id.btn3:
                pullParse();
                break;
            default:
                break;
        }

    }

    private void pullParse() {
        StringBuilder sb = new StringBuilder("");
        Resources res = getResources();
        XmlResourceParser xrp = res.getXml(R.xml.subject);

        int counter = 0;

        try {

            // 判断是否到了文件的结尾
            while (xrp.getEventType() != XmlPullParser.END_DOCUMENT) {
                //文件的内容的起始标签开始，这里的起始标签是subject.xml文件里面<subjects>标签下面的第一个标签
                int eventType=xrp.getEventType();
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case  XmlPullParser.START_TAG:
                        String tagname = xrp.getName();
                        if (tagname.endsWith("language")) {
                            counter++;
                            sb.append("这是第" + counter + "种语言"+"\n");
                            //可以调用XmlPullParser的getAttributte()方法来获取属性的值
                            sb.append("语言id是："+xrp.getAttributeValue(0)+"\n");
                        }
                        else if(tagname.equals("name")){
                            //可以调用XmlPullParser的nextText()方法来获取节点的值
                            sb.append("语言名称是："+xrp.nextText()+"\n");
                        }
                        else if(tagname.equals("usage")){
                            sb.append("用途是："+xrp.nextText()+"\n");
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                    case XmlPullParser.TEXT:
                        break;
                }
                //解析下一个事件
                xrp.next();
            }
            //StringBuilder要调用toString()方法并显示
            content.setText(sb.toString());
        } catch (XmlPullParserException e) {

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void domParse() {
        //打开xml文件到输入流
        try {
            InputStream stream = getAssets().open("subject.xml");

            //得到DocumentBuilderFactory对象
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            //得到DocumentBuilder对象
            DocumentBuilder builder = builderFactory.newDocumentBuilder();
            //建立Document存放整个xml的Document对象数据
            Document document = builder.parse(stream);
            //得到根节点
            Element element = document.getDocumentElement();
            //获取根节点下的所有lanaguage的节点
            NodeList list = element.getElementsByTagName("language");
            //遍历所有节点
            for (int i = 0; i < list.getLength(); i++) {
                //获取language下的所有子元素
                Element lan = (Element) list.item(i);

                content.append(lan.getAttribute("id") + "\n");

                //获取language的子元素 name 并显示
                content.append(lan.getElementsByTagName("name").item(0).getTextContent()+"\n");
                //获取language的子元素usage 并显示
                content.append(lan.getElementsByTagName("usage").item(0).getTextContent()+"\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
    }

    private void naviveParse() {

       // EntityStudent student = new EntityStudent();

        try {
            //从assets中获取json文件
            InputStreamReader isr = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("assets/" + "student.json"));
            //将字节流转成字符流
            BufferedReader bfr = new BufferedReader(isr);
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bfr.readLine()) != null) {
                stringBuilder.append(line);
            }
            //将json转成字符串
            JSONObject root = new JSONObject(stringBuilder.toString());

            //根据键值取出对应信息
            System.out.println("root==" + root.getString("cat"));

            JSONArray arry = root.getJSONArray("student");

            for (int i = 0; i < arry.length(); i++) {
                JSONObject stud = arry.getJSONObject(i);
                System.out.println("======================");
                System.out.print("id=" + stud.getInt("id") + ",");
                System.out.print("name=" + stud.getString("name") + ",");
                System.out.print("sex=" + stud.getString("sex") + ",");
                System.out.print("age=" + stud.getInt("age") + ",");
                System.out.println("height=" + stud.getInt("height") + ",");
                //依次关流
                bfr.close();
                isr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }
}
